<?php

namespace app\api\controller;

use app\common\model\AuthGroup;
use app\common\model\AuthMenu;
use app\common\logic\Auth;
use think\facade\Validate;
use think\facade\Db;
use app\common\logic\Data;
use app\common\model\Version;
use app\lib\exception\ApiException;
use app\lib\Result;
use app\common\model\UserSetting;

class User extends Base
{
  public function info()
  {
    $user    = $this->user;
    $user['role'] = $this->getrole(0);
    return json(['code' => 200, 'data' => $user, 'msg' => '获取成功']);
  }
  public function getrole($outFun = 1)
  {
    if ($this->user['is_admin'] === 1) {
      $where = ['status' => 1];
    } else {
      $getRulesInfo = getAuthGroupById($this->user['groupId'], $this->p_mid);
      $getRulesInfo['rules'] = $getRulesInfo['rules'] . ',' . $getRulesInfo['halfrules'];
      $getRules['name'] = $getRulesInfo['title'];
      $getRules['describe'] = $getRulesInfo['desc'];
      $rulesArr = explode(',', $getRulesInfo['rules']);
      $where = ['id' => ['in', $rulesArr], 'status' => 1];
    }
    $rulesList = AuthMenu::where($where)->order('sort', ' asc')->select()->toArray();
    $access = (new Data)->listToTreeMulti($rulesList, 0, 'id', 'pid', 'children');
    $routers = [];
    $permissionList = [];
    foreach ($access as $v) {
      foreach ($v['children'] as $vo) {
        $actArr = [];
        $act2Arr = [];
        $per['roleId'] = $this->user['groupId'];
        $per['permissionId'] = $vo['key'];
        $per['permissionName'] = $vo['title'];
        foreach ($vo['children'] as $vo2) {
          if (isset($vo2['children']) && !empty($vo2['children'])) {
            foreach ($vo2['children'] as $vo3) {
              $act2 = $act['action'] = $vo3['key'];
              $act['describe'] = $vo3['title'];
              $act['defaultCheck'] = true;
              array_push($actArr, $act);
              array_push($act2Arr, $act2);
            }
          }
          $act2 = $act['action'] = $vo2['key'];
          $act['describe'] = $vo2['title'];
          $act['defaultCheck'] = true;
          array_push($actArr, $act);
          array_push($act2Arr, $act2);
        }
        $per['actions'] = json_encode($actArr);
        $per['actionEntitySet'] = $actArr;
        $per['actionList'] = $act2Arr;
        $per['dataAccess'] = null;
        array_push($routers, $per);
        array_push($permissionList, $vo['key']);
      }
    }
    $getRules['permissions'] = $routers;
    $getRules['permissionList'] = $permissionList;
    if ($outFun == 1) {
      return json(['code' => 200, 'data' => $getRules, 'msg' => '获取成功']);
    } else {
      return $getRules;
    }
  }
  public function getmenu()
  {
    if ($this->user['is_admin'] == 1) {
      $where = ['status' => [1,2,3], 'type' => [1, 2]];
    } else {
      $ruleString = Auth::getRuleId($this->user['groupId']);
      $rulesArr = explode(',', $ruleString);
      $where = ['id' => $rulesArr, 'status' => 1, 'type' => [1, 2]];
    }
    $rulesList = AuthMenu::where($where)->order('sort', 'asc')->select()->toArray();
    foreach ($rulesList as &$vo) {
      if (empty($vo['filePath'])) {
        $vo['filePath'] = $vo['key'];
      }
      $vo['hideChildrenInMenu'] = ($vo['hideChildrenInMenu'] == 1) ? true : false;
      $vo['hidden'] = ($vo['hidden'] == 1) ? true : false;
      $vo['icon'] = 'anticon-' . $vo['icon'];
    }
    return json(['code' => 200, 'data' => $rulesList, 'msg' => '获取成功']);
  }
  private static function getMenuTree($data)
  {
    $treeData = array();
    foreach ($data as $vo) {
      if (isset($vo['children'])) {
        $vo1['key'] = $vo['key'];
        $vo1['filePath'] = $vo['filePath'];
        $vo1['icon'] = $vo['icon'];
        $vo1['component'] = $vo['component'];
        $vo1['title'] = $vo['title'];
        $vo1['hideChildrenInMenu'] = $vo['hideChildrenInMenu'];
        $vo1['hidden'] = $vo['hidden'];
        $vo1['children'] = self::getMenuTree($vo['children']);
        $treeData[] = $vo1;
      }
    }
    return $treeData;
  }
  public function refresh_token()
  {
    $hasUser = Db::name('manager')->field('is_admin,groupId,username,avatar')->where('id', $this->uid)->find();
    $rules = Auth::getRuleId($hasUser['groupId']);
    $tokenArr['rules'] = Auth::getRuleKey($rules);
    $tokenArr['userToken'] = $this->redis->get('token-' . $this->uid);
    //用户登录有效期
    $loginExpireTime = config('app.SYS_STATIC.login_expire');
    // 存储用户token
    $tokenArr['Expire'] = $loginExpireTime * 1000;
    $tokenArr['loginExpire'] = ($loginExpireTime + time())*1000;
    $tokenArr['isSuper'] = $hasUser['is_admin'];
    $tokenArr['username'] = $hasUser['username'];
    $tokenArr['avatar'] = $hasUser['avatar'];
    return Result::Success($tokenArr);
  }
  // 删除redis缓存
  private function delRedisCache($data = [])
  {
    delRedisCache('getmanager_list_by_prid-' . $this->p_mid);
    if (isset($data['id'])) {
      delRedisCache('getAuthApiListById-' . $this->user['id']);
      delRedisCache('getmanager_by_id-' . $this->p_mid . '-' . $data['id']);
    }
    delRedisCache('getManagerPage1ListByMid-' . $this->p_mid);
  }
  public function resetDevKey()
  {
    $hasSetting = UserSetting::where('uid',$this->uid)->find();
    $this->redis->del('libs:userSetting:info:' . $this->uid);
    if (empty($hasSetting)) {
      $settingData['uid'] = $this->uid;
      $settingData['username'] = $this->username;
      $settingData['dev_key'] = create_uuid('DEV-');
      UserSetting::insert($settingData);
    }else{
      UserSetting::where('uid',$this->uid)->update(['dev_key'=>create_uuid('DEV-')]);
    }
    return Result::Success('','重置成功');
  }
  public function resetSecretKey()
  {
    $hasSetting = UserSetting::where('uid',$this->uid)->find();
    $this->redis->del('libs:userSetting:info:' . $this->uid);
    if (empty($hasSetting)) {
      $settingData['uid'] = $this->uid;
      $settingData['username'] = $this->username;
      $settingData['secret_key'] = create_uuid('CSK-');
      UserSetting::insert($settingData);
    }else{
      $this->redis->del('userInfo:dev_key:' . $hasSetting['dev_key']);
      UserSetting::where('uid',$this->uid)->update(['secret_key'=>create_uuid('CSK-')]);
    }
    return Result::Success('','重置成功');
  }
  public function getUserSetting()
  {
    $hasSetting = $this->redisCache->getUserSetting($this->uid);
    unset($hasSetting['id']);
    return Result::Success($hasSetting);
  }
}
